<?php

namespace plugin\cms\app\bll;

use app\bll\User;
use core\attribute\Template;
use Exception;
use support\Db;
use Throwable;

/**
 * 积分兑换
 */
class PointsExchange
{

    /**
     * 查找一条兑换记录
     *
     * @param integer $uid 用户ID
     * @param integer $mid
     * @param integer $cid
     * @param integer $contentid
     * @param string $otherparam
     * @return array
     */
    public function find(
        int $uid,
        int $cid,
        int $contentid,
        string $otherparam = ''
    ): array {
        $table = Db::table('cms_points_exchange')
            ->where('uid', '=', $uid)
            ->where('cid', '=', $cid)
            ->where('contentid', '=', $contentid)
            ->when($otherparam != '', function ($query) use ($otherparam) {
                return $query->where('otherparam', '=', $otherparam);
            })
            ->first();
        return $table === null ? [] : get_object_vars($table);
    }


    /**
     * 兑换积分
     *
     * @param array $data
     * @return void
     */
    public function add(
        int $id,
        int $cid,
        int $siteid,
        int $uid,
    ) {

        Db::beginTransaction();
        try {
            $bllContent = new Content();
            $content =  $bllContent->find($id, $cid, $siteid);
            if (!$this->isExchange($uid, $cid, $content['id'])) {
                $bllUser = new User();
                $userinfo = $bllUser->find($uid);
                if ($content['points'] > $userinfo['integral']) {
                    throw new Exception('积分不够');
                }

                $data = [
                    'cid'        => $cid,
                    'siteid'     => $siteid,
                    'contentid'  => $id,
                    'uid'        => $uid,
                    'point'      => $content['points'],
                    'createtime' => date('Y-m-d H:i:s')
                ];
                Db::table('cms_points_exchange')
                    ->insertGetId($data);

                //扣除积分
                $integral = $userinfo['integral'] - $content['points'];

                Db::table('rc_user')
                    ->where('id', '=', $uid)
                    ->update(['integral' => $integral]);

                //写入日志
                Db::table('rc_user_integral_log')
                    ->insert([
                        'uid'      => $uid,
                        'ruleid'   => 0,
                        'remark'   => '兑换文章《' . $content['title'] . '》阅读权限',
                        'addsub'   => 2,
                        'integral' => $content['points'],
                        'addtime' => time()
                    ]);
            }
            Db::commit();
        } catch (Throwable $ex) {
            Db::rollBack();
            throw $ex;
        }
    }

    /**
     * 判断是否兑换过谋篇文章
     *
     * @param integer $uid 用户ID
     * @param integer $mid 模型ID
     * @param integer $cid 栏目ID
     * @param integer $contentid 内容ID
     * @param string $otherparam 额外参数
     * @return boolean
     */
    #[Template]
    public function isExchange(
        int $uid,
        int $cid,
        int $contentid,
        string $otherparam = ''
    ): bool {

        $info = $this->find(
            uid: $uid,
            cid: $cid,
            contentid: $contentid,
            otherparam: $otherparam
        );
        return count($info) != 0;
    }
}
